package com.tuiyun.jxgl.action;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.transaction.annotation.Transactional;

import com.tuiyun.jxgl.bean.Driver;
import com.tuiyun.jxgl.bean.Student;
import com.tuiyun.jxgl.bean.Stuselectdriver;
import com.tuiyun.jxgl.dao.DriverHome;
import com.tuiyun.jxgl.dao.StuselectdriverHome;

public class ViewDriverAction {
	
	private int driverid;
	
	private Driver d;
	
	private boolean canComment = false;
	
	private String msg;
	
	private DriverHome dh;
	
	private StuselectdriverHome ssh;
	
	private int countOfComment;
	
	private List<Stuselectdriver> ssds;
	@Transactional
	public String execute(){
		canComment = false;
		msg = "";
		List<Stuselectdriver> ss = ssh.findbyDriver(driverid);
		int size = 12;
		int sum = 12*4;
		for(Stuselectdriver t : ss){
			if(t.getComment_time() != null){
				size ++;
				sum += t.getRate();
			}
		}
		d = dh.findById(driverid);
		if(size != 0){
			d.setRate(sum*1.0f/size);
			dh.attachDirty(d);
			d = dh.findById(driverid);
		}
		countOfComment = ssh.getDriverCommentCount(driverid);
		ssds = ssh.findbyDriver(driverid);
		Subject s = SecurityUtils.getSubject();
		if(s.isAuthenticated()){
			Object o = s.getPrincipal();
			if(o instanceof Student){
				Student stu = (Student)o;
				if(stu.getName().equalsIgnoreCase("admin") == false){
					Stuselectdriver sd = ssh.findByStudent(stu.getId());
					if(sd != null && sd.getDriver().getId().intValue() == driverid){
						if(sd.getComment_time() != null){
							msg = "只能评价老师一次！";						
						}else{
							canComment = true;
						}
					}else{
						//not a student
						msg = "您还不是该老师的学生！";
					}
				}				
			}
		}else{
			return "login";
		}
		if(d == null){
			return "error";
		}
		return "success";
	}

	public int getDriverid() {
		return driverid;
	}

	public void setDriverid(int driverid) {
		this.driverid = driverid;
	}

	public DriverHome getDh() {
		return dh;
	}

	public void setDh(DriverHome dh) {
		this.dh = dh;
	}

	public Driver getD() {
		return d;
	}

	public void setD(Driver d) {
		this.d = d;
	}

	public StuselectdriverHome getSsh() {
		return ssh;
	}

	public void setSsh(StuselectdriverHome ssh) {
		this.ssh = ssh;
	}

	public boolean isCanComment() {
		return canComment;
	}

	public void setCanComment(boolean canComment) {
		this.canComment = canComment;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public int getCountOfComment() {
		return countOfComment;
	}

	public void setCountOfComment(int countOfComment) {
		this.countOfComment = countOfComment;
	}

	public List<Stuselectdriver> getSsds() {
		return ssds;
	}

	public void setSsds(List<Stuselectdriver> ssds) {
		this.ssds = ssds;
	}

}
